package com.learn.security.modules.security.weixin;

import com.learn.security.modules.security.CustomUserDetailsService;
import com.learn.security.modules.security.LoginUserType;
import com.learn.security.modules.wx.mp.config.WxMpProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 短信登陆鉴权 Provider，要求实现 AuthenticationProvider 接口
 *
 * @author jitwxs
 * @since 2019/1/9 13:59
 */
@Slf4j
@Data
public class WeixinCodeAuthenticationProvider implements AuthenticationProvider {

    private static final String OPEN_ID = "openId";

    /**
     * 获取用户信息
     */
    private CustomUserDetailsService userDetailsService;

    /**
     * 微信服务
     */
    private WxMpService wxService;
    /**
     * 微信配置
     */
    private WxMpProperties properties;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WeixinCodeAuthenticationToken authenticationToken = (WeixinCodeAuthenticationToken) authentication;

        String code = (String) authenticationToken.getPrincipal();
        // 校验openid
        WxMpUser mpUser = checkOauth2Code(code);
        // 获取用户数据
        UserDetails userDetails = userDetailsService.loadUserByOpenId(LoginUserType.WEIXIN_OPEN_ID, mpUser);

        // 此时鉴权成功后，应当重新 new 一个拥有鉴权的 authenticationResult 返回
        WeixinCodeAuthenticationToken authenticationResult = new WeixinCodeAuthenticationToken(userDetails, userDetails.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    private WxMpUser checkOauth2Code(String code) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        List<WxMpProperties.MpConfig> configs = properties.getConfigs();
        String appId = configs.get(0).getAppId();
        if (!this.wxService.switchover(appId)) {
            log.info(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
            throw new BadCredentialsException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
        }

        try {
            WxMpOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxMpUser mpUser = wxService.getOAuth2Service().getUserInfo(accessToken, null);
            if (mpUser == null){
                log.info("登录失败,获取用户微信数据为空");
                throw new BadCredentialsException("登录失败,获取用户微信数据为空");
            }
            // 设置openid到session
            HttpSession session = request.getSession();
            session.setAttribute(session.getId(), mpUser.getOpenId());
            log.info("微信登录sessionId:{}, openId:{}", request.getSession().getId(), mpUser.getOpenId());
            return mpUser;
        } catch (WxErrorException e) {
            log.error("微信登录异常", e);
            throw new BadCredentialsException("登录异常");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 判断 authentication 是不是 WeixinCodeAuthenticationToken 的子类或子接口
        return WeixinCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}